<?php

/**
 * @return true if all data are valid, false otherwise
 */
function checkData(array $categoriesEnBase, $categories, $prixmin, $prixmax, array $etatsEnBase, $etats)
{    
    $categoriesAutorisees = array();
    foreach ($categoriesEnBase as $c)   $categoriesAutorisees[] = $c->getId();
    
    $etatsAutorises = array();
    foreach ($etatsEnBase as $e)   $etatsAutorises[] = $e->getId();
    
    // categories
    if (!empty($categories)) {
        foreach ($categories as $c) {
            if (!in_array($c, $categoriesAutorisees)) {
                return false;
            }
        }
    }
    
    // prixmin
    // TODO check slider minvalue
    if (!empty($prixmin)) {
        if(filter_var($prixmin, FILTER_VALIDATE_FLOAT) === false) {
            return false;
        }
    }
    
    // prixmax
    // TODO check slider maxvalue
    if (!empty($prixmax)) {
        if(filter_var($prixmax, FILTER_VALIDATE_FLOAT) === false) {
            return false;
        }
    }
    
    // etats
    if (!empty($etats)) {
        foreach ($etats as $e) {
            if (!in_array($e, $etatsAutorises)) {
                return false;
            }
        }
    }
    
    return true;
}

function getProductsWithFilters($em, $categories, $prixmin, $prixmax, $etats)
{
    $qb = $em->createQueryBuilder();
    $qb->select('p')
        ->from('Application\Model\Entity\Produit', 'p');

    // Apply filters
    $where = '';
    
    if (!empty($prixmin) && !empty($prixmax)) {
        $where .= "p.prix >= $prixmin and p.prix <= $prixmax";
    } else if (!empty($prixmin)) {
        $where .= "p.prix >= $prixmin";
    } else if (!empty($prixmax)) {
        $where .= "p.prix <= $prixmax";
    }
    
    if ($categories !== null) {
        if (!empty($where)) $where .= " and ";
        $where .= "p.categorie in (?1)";
        $qb->setParameter(1, $categories);
    }
    if ($etats !== null) {
        if (!empty($where)) $where .= " and ";
        $where .= "p.etat in (?2)";
        $qb->setParameter(2, $etats);
    }
    
    if (!empty($where)) {
        $qb->where($where);
    }
    $query = $qb->getQuery();
    //var_dump($qb->getDql());
    return $query->getResult();
}